package com.qxsx.midi.activity.me;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.qxsx.midi.R;
import com.qxsx.midi.activity.base.BaseActivity;
import com.qxsx.midi.activity.main.DownLodeActivity;
import com.qxsx.midi.db.MyMusicFileDBTool;
import com.qxsx.midi.model.MyMusicFile;
import com.qxsx.midi.utils.CustomProgress;
import com.qxsx.midi.utils.MyNet;
import com.qxsx.midi.utils.callBackJsonArray;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.controller.UMServiceFactory;
import com.umeng.socialize.controller.UMSocialService;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.sso.UMSsoHandler;
import com.umeng.socialize.weixin.controller.UMWXHandler;
import com.umeng.socialize.weixin.media.CircleShareContent;
import com.umeng.socialize.weixin.media.WeiXinShareContent;

import net.tsz.afinal.FinalBitmap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Timer;
import java.util.TimerTask;

public class DownLodeMp3Activity extends BaseActivity implements View.OnClickListener {
    TimerTask timeTask;
    private CustomProgress customProgress;

    ImageView img_mp3_bg;
    ImageView btnPlay;          // 播放按钮
    TextView txtCurTime;     // 当前播放的时间点
    SeekBar seekBar;        // seek bar
    ImageView btnShare;       // 分享
    TextView totalTime;      // 总共的时间点
    TextView txtMp3Title;      // 总共的时间点
    TextView txtMp3Desc;      // 总共的时间点
    private LinearLayout btn_download;
    private LinearLayout btn_downloaded;
    Timer timer;          // 计时器
    boolean playFinish; // 播放完成
    boolean isChanging = false; //
    private MediaPlayer mp = new MediaPlayer();
    private String _id;//音频ID
    private String _title;//标题

    String _url, _name, _img, _desc, _major, _grade;
    //
    private FinalBitmap finalImageLoader;
    private File path;//所有音频文件的根目录
    private String fileName;//文件名称
    // 首先在您的Activity中添加如下成员变量
    final UMSocialService mController = UMServiceFactory.getUMSocialService("com.umeng.share");

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mp3_player);

        Intent intent = getIntent();
       // _id = intent.getStringExtra("_id");
        _title = intent.getStringExtra("_name");
        _url = intent.getStringExtra("_music");
        _desc = intent.getStringExtra("_content");

        finalImageLoader = FinalBitmap.create(this);
        finalImageLoader.configLoadingImage(R.mipmap.binner);
        finalImageLoader.configLoadfailImage(R.mipmap.binner);

        setTitle(_title);
        setNavBtn(R.mipmap.back, 0);

        findById();
        //inItData();
        // 配置需要分享的相关平台
        addWXPlatform();
        // 设置分享的内容
        setShareContent();

        //配置缓存机制
        path = getDiskCacheDir(DownLodeMp3Activity.this, "Music");
        if (!path.exists()) {
            path.mkdirs();
        }


    }

    private void inItData() {
        customProgress = CustomProgress.show(DownLodeMp3Activity.this, "正在加载中....", true, null);

        JSONArray array = new JSONArray();
        JSONObject object = new JSONObject();

        try {
            object.put("song_id", _id);
            array.put(object);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        MyNet.doPostJsonArray("514", array, new callBackJsonArray() {
            @Override
            public void run(Object code, Object message, JSONArray array) {
                try {
                    if ("200".equals(code.toString())) {
                        JSONObject object = array.getJSONObject(0);
                        String _id = object.getString("id");
                        _name = object.getString("song_name");
                        _desc = object.getString("song_brief");
                        _img = object.getString("cover_img");
                        _url = object.getString("song_url");
                        _major = object.getString("major_id");
                        _grade = object.getString("grade_num");
                        String a[] = _url.split("/");
                        int i = a.length;
                        fileName = a[i - 1];
                        txtMp3Title.setText(_name);
                        txtMp3Desc.setText(_desc);
                        finalImageLoader.display(img_mp3_bg, _img);

                        CheckFile(fileName, _url);
                    } else {
                        Log.e("code", code.toString());
                        Log.e("message", code.toString());
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                customProgress.dismiss();

            }
        });
    }


    /**
     * @return
     * @功能描述 : 添加微信平台分享
     */
    private void addWXPlatform() {
        String appId = "wxee179977f8060101";
        String appSecret = "aabc6f5feec80e1d9249f7a0ce9d1cee";
        UMWXHandler wxHandler = new UMWXHandler(DownLodeMp3Activity.this, appId, appSecret);
        wxHandler.addToSocialSDK();
        UMWXHandler wxCircleHandler = new UMWXHandler(DownLodeMp3Activity.this, appId, appSecret);
        wxCircleHandler.setToCircle(true);
        wxCircleHandler.addToSocialSDK();
    }

    private void setShareContent() {

        mController.setShareContent("MIDI");
        mController.setShareMedia(new UMImage(DownLodeMp3Activity.this,
                R.mipmap.ic_launcher));

        WeiXinShareContent weiXinShareContent = new WeiXinShareContent();
        weiXinShareContent.setShareContent("这是一个先进的 MIDI 音乐分享网站,云集了来自中国和世界各地的 MIDI爱好者,每天有大量 MIDI 音乐文件上传发布并供您下载");
        weiXinShareContent.setTitle("MIDI");
        weiXinShareContent.setShareImage(new UMImage(DownLodeMp3Activity.this,
                R.mipmap.midi));
        weiXinShareContent.setTargetUrl("http://www.midishow.com");
        mController.setShareMedia(weiXinShareContent);

        // 设置朋友圈分享的内容
        CircleShareContent circleMedia = new CircleShareContent();
        circleMedia.setShareContent("这是一个先进的 MIDI 音乐分享网站,云集了来自中国和世界各地的 MIDI爱好者,每天有大量 MIDI 音乐文件上传发布并供您下载");
        circleMedia.setTitle("MIDI");
        circleMedia.setShareMedia(new UMImage(DownLodeMp3Activity.this,
                R.mipmap.midi));
        circleMedia.setTargetUrl("http://www.midishow.com");
        mController.setShareMedia(circleMedia);

    }


    private void findById() {
        // 播放器
        btnPlay = (ImageView) findViewById(R.id.btn_play);
        img_mp3_bg = (ImageView) findViewById(R.id.img_mp3_bg);

        txtCurTime = (TextView) findViewById(R.id.txt_cur_time);
        totalTime = (TextView) findViewById(R.id.txt_total_time);
        seekBar = (SeekBar) findViewById(R.id.mp3_seekbar);
        btnShare = (ImageView) findViewById(R.id.btn_mp3_share);
        txtMp3Title = (TextView) findViewById(R.id.txt_mp3_title);
        txtMp3Desc = (TextView) findViewById(R.id.txt_mp3_desc);
        btn_download = (LinearLayout) findViewById(R.id.btn_download);
        btn_downloaded = (LinearLayout) findViewById(R.id.btn_downloaded);
        // callback
        btnPlay.setOnClickListener(this);
        btnShare.setOnClickListener(this);

        btn_download.setVisibility(View.GONE);
        btn_downloaded.setVisibility(View.VISIBLE);

        mp = new MediaPlayer();

        mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                onPlayerEnd();
            }
        });
        mp.setOnErrorListener(new MediaPlayer.OnErrorListener() {
            @Override
            public boolean onError(MediaPlayer mp, int what, int extra) {
                Log.e("music", "comp");
                return false;
            }
        });
        mp.setOnBufferingUpdateListener(new MediaPlayer.OnBufferingUpdateListener() {
            @Override
            public void onBufferingUpdate(MediaPlayer mp, int percent) {
            }
        });
        mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                play();
            }
        });


        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                isChanging = true;
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                mp.seekTo(seekBar.getProgress());
                isChanging = false;
                resume();
            }
        });
        String a[] = _url.split("/");
        int i = a.length;
        fileName = a[i - 1];
        txtMp3Title.setText(_title);
        txtMp3Desc.setText(_desc);
        finalImageLoader.display(img_mp3_bg, _img);

        CheckFile(fileName, _url);


    }

//    public void downlode(View v) {
//
//        Intent intent1 = new Intent(DownLodeMp3Activity.this, DownLodeActivity.class);
//        intent1.putExtra("_url", _url);//传递data
//        startActivityForResult(intent1, 1001);
//    }

    @Override
    protected void HandleTitleBarEvent(TitleBar component, View v) {
        switch (component) {
            case LEFT:
                finish();
                break;
        }
    }

    @Override
    protected void onDestroy() {
        if (mp != null) {
            mp.stop();
            mp.release();
        }
        super.onDestroy();
        mp = null;
    }

    @Override
    public void onClick(View v) {
        if (v == btnPlay) {
            if (mp != null) {
                if (mp.isPlaying()) {
                    pause();
                } else if (playFinish) {
                    play();
                } else {
                    resume();
                }
            }
        } else if (v == btnShare) {
            if (mp != null) {
                mController.getConfig().setPlatforms(SHARE_MEDIA.WEIXIN,
                        SHARE_MEDIA.WEIXIN_CIRCLE);
                mController.openShare(DownLodeMp3Activity.this, false);
            }
        }
    }

    /**
     * 检查本地文件是否存在
     *
     * @param fileName
     */
    public void CheckFile(String fileName, String url) {

        if (fileIsExists(path + "/" + fileName) == false) {
//            btn_download.setVisibility(View.VISIBLE);
//            btn_downloaded.setVisibility(View.GONE);
            Log.e("不存在该文件", "不存在该文件");
            try {
                mp.setDataSource(url);
                mp.prepareAsync();// 开始在后台缓冲音频文件并返回
            } catch (Exception e) {
                e.printStackTrace();
            }

        } else {

            Log.e("文件", "存在该文件");
            try {

                mp.setDataSource(path + "/" + fileName);
                mp.prepareAsync();// 开始在后台缓冲音频文件并返回

            } catch (Exception e) {
                e.printStackTrace();
            }
        }


    }

    /**
     * 判断文件是否存在
     *
     * @param strFile
     * @return
     */
    public boolean fileIsExists(String strFile) {
        try {
            File f = new File(strFile);
            if (!f.exists()) {
                return false;
            }

        } catch (Exception e) {
            return false;
        }

        return true;
    }

    void play() {
        btnPlay.setImageResource(R.mipmap.btn_mp3_pause);
        Log.e("fuck ", "" + mp.getCurrentPosition() + "  " + mp.getDuration() + " ");
        seekBar.setProgress(0);
        txtCurTime.setText("00:00");

        int min = mp.getDuration() / 1000 / 60;
        int sec = mp.getDuration() / 1000 % 60;
        String str = String.format("%02d:%02d", min, sec);
        totalTime.setText(str);

        mp.start();
        playFinish = false;
        seekBar.setMax(mp.getDuration());

        timer = new Timer();
        timeTask = new TimerTask() {
            @Override
            public void run() {
                if (isChanging) {
                    return;
                }
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (mp != null && mp.isPlaying()) {
                            int min = mp.getCurrentPosition() / 1000 / 60;
                            int sec = mp.getCurrentPosition() / 1000 % 60;
                            String str = String.format("%02d:%02d", min, sec);
                            txtCurTime.setText(str);
                            seekBar.setProgress(mp.getCurrentPosition());
                        }
                    }
                });
            }
        };
        timer.schedule(timeTask, 0, 10);
    }


    void resume() {


        mp.start();
        btnPlay.setImageResource(R.mipmap.btn_mp3_pause);
    }

    void pause() {
        mp.pause();
        btnPlay.setImageResource(R.mipmap.btn_mp3_play);
    }


    void onPlayerEnd() {
        btnPlay.setImageResource(R.mipmap.btn_mp3_play);
        seekBar.setProgress(0);
        playFinish = true;
    }

    protected void onPause() {
        if (mp != null) {
            if (mp.isPlaying()) {
                mp.pause();
            }
        }
        super.onPause();
    }

    protected void onResume() {

        if (mp != null) {
            if (!mp.isPlaying()) {
                mp.start();
            }
        }

        super.onResume();
    }


//    @Override
//    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//        super.onActivityResult(requestCode, resultCode, data);
//        /**使用SSO授权必须添加如下代码 */
//        if (resultCode == 1001) {
//
//            if (fileIsExists(path + "/" + fileName) == false) {
////                btn_download.setVisibility(View.VISIBLE);
////                btn_downloaded.setVisibility(View.GONE);
//
//            } else {
////                btn_download.setVisibility(View.GONE);
////                btn_downloaded.setVisibility(View.VISIBLE);
//                MyMusicFileDBTool myFileDBTool = null; // 执行对数据库的相关操作
//                myFileDBTool = new MyMusicFileDBTool(DownLodeMp3Activity.this);
//                MyMusicFile myMusicFile = new MyMusicFile(_major, _grade,
//                        _name, _desc, "", path + "/" + fileName);
//                myFileDBTool.insertOne(myMusicFile);
//            }
//        }
//
//        UMSsoHandler ssoHandler = mController.getConfig().getSsoHandler(requestCode);
//        if (ssoHandler != null) {
//            ssoHandler.authorizeCallBack(requestCode, resultCode, data);
//        }
//
//
//    }

    /**
     * 取缓存地址
     *
     * @param context    获取到的系统路径
     * @param uniqueName 对不同类型的数据进行区分而设定的一个唯一值
     * @return
     */
    public File getDiskCacheDir(Context context, String uniqueName) {
        String cachePath;
        if (Environment.MEDIA_MOUNTED.equals(Environment
                .getExternalStorageState())
                || !Environment.isExternalStorageRemovable()) {
            cachePath = context.getExternalCacheDir().getPath();
        } else {
            cachePath = context.getCacheDir().getPath();
        }
        // 将系统的路径和唯一值拼接
        return new File(cachePath + File.separator + uniqueName);
    }

    /**
     * 获取当前系统的版本号
     *
     * @param context
     * @return
     */
    public int getAppVersion(Context context) {
        try {
            PackageInfo info = context.getPackageManager().getPackageInfo(
                    context.getPackageName(), 0);
            return info.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return 1;
    }

    /**
     * 用MD5去加密URL作为文件名
     *
     * @param key
     * @return
     */
    public String hashKeyForDisk(String key) {
        String cacheKey;
        try {
            final MessageDigest mDigest = MessageDigest.getInstance("MD5");
            mDigest.update(key.getBytes());
            cacheKey = bytesToHexString(mDigest.digest());
        } catch (NoSuchAlgorithmException e) {
            cacheKey = String.valueOf(key.hashCode());
        }
        return cacheKey;
    }

    private String bytesToHexString(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < bytes.length; i++) {
            String hex = Integer.toHexString(0xFF & bytes[i]);
            if (hex.length() == 1) {
                sb.append('0');
            }
            sb.append(hex);
        }
        return sb.toString();
    }
}
